package org.example.JVM.ASM.UseASM;


import jdk.internal.org.objectweb.asm.Type;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import static org.objectweb.asm.Opcodes.*;

/**
 * @description:
 * @author: farprt
 * @create: 2022-11-16 23:40
 **/
public class MainMethodWriter extends MethodVisitor {

    private MethodVisitor methodVisitor;

    public MainMethodWriter(MethodVisitor methodVisitor) {
        super(Opcodes.ASM6, methodVisitor);
        this.methodVisitor = methodVisitor;
    }

    /**
     * @param
     * @return:
     * @Author: farprt
     * @date: 2022/11/16 23:47
     * @description: 自定义MethodVisitor，实现在main方法里插入一行输出hello world
     */
    @Override
    public void visitCode() {
        super.visitCode();
        methodVisitor.visitFieldInsn(GETSTATIC
                , Type.getInternalName(System.class)
                , "out"
                , Type.getDescriptor(System.out.getClass()));
        methodVisitor.visitLdcInsn("hello world!");
        methodVisitor.visitMethodInsn(INVOKEVIRTUAL
                , Type.getInternalName(System.out.getClass())
                , "println"
                , "(Ljava/lang/String;)V"
                , false);
    }

    @Override
    public void visitInsn(int opcode) {
        if (opcode == RETURN) {
            // 如果操作码等于return指令的操作码，则在return指令之前加入一些字节码指令
        }
        super.visitInsn(opcode);
    }
}